package com.bfxy.rabbit.api;

import com.bfxy.rabbit.api.exception.MessageRuntimeException;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @describte:建造者模式建造Message
 * @program:rabbit-parent
 * @author:zhengdp
 * @create:2021-09-14 20:59:12
 **/
public class MessageBuilder {
    /*建造者模式的类中的属性必须与要建造的类的属性相同*/

    private String messageId;
    private String topic;
    private String routingKey = "";
    private Map<String,Object> attributes = new HashMap<>();
    private int delayMills;
    private String messageType = MessageType.CONFIRM;

    /**
     * 构造函数的私有化
     */
    private MessageBuilder(){}

    /**
     * 对外提供一个 静态的创建方法
     * @return
     */
    public static MessageBuilder create(){
        return new MessageBuilder();
    }

    /**
     * 实现一个链式调用
     */

    public MessageBuilder withMessageId(String messageId){
        this.messageId = messageId;
        return this;
    }

    public MessageBuilder withTopic(String topic){
        this.topic = topic;
        return this;
    }

    public MessageBuilder withRoutingKey(String routingKey){
        this.routingKey = routingKey;
        return this;
    }

    public MessageBuilder withAttributes(Map attributes){
        this.attributes = attributes;
        return this;
    }

    public MessageBuilder withAttribute(String key,Object value){
        this.attributes.put(key,value);
        return this;
    }

    public MessageBuilder withDelayMills(int delayMills){
        this.delayMills = delayMills;
        return this;
    }

    public MessageBuilder withMessageType(String messageType){
        this.messageType = messageType;
        return this;
    }

    public Message build(){
        // 个性化判断
        // messageId is null
        if(messageId == null){
            messageId = UUID.randomUUID().toString();
        }
        // topic is null
        if(topic == null){
            throw new MessageRuntimeException("topic is null");
        }
        Message message = new Message( messageId,  topic,
                 routingKey,  attributes, delayMills,  messageType);
        return message;
    }
}
